import { fetchStoredToken } from "../../utils/token";
const app = getApp();
Page({
  data: {
    avatarUrl: app.globalData.defaultAvatarUrl,
  },
  onChooseAvatar(event) {
    this.setData({
      avatarUrl: event.detail.avatarUrl,
    });
  },
  improveUserInfo(event) {
    let { avatarUrl } = this.data;
    let { nickname } = event.detail.value;
    const token = fetchStoredToken();
    if (!token) {
      return wx.showToast({
        title: "未登录",
        icon: "error",
      });
    }
    wx.uploadFile({
      filePath: avatarUrl, //上传的图片的临时路径
      name: "avatar", //上传的图片的字段名
      url: `${app.globalData.baseURL}/upload`, //上传图片的URL地址
      formData: {
        //除了图片之外。额外上传的字段名和字段值
        nickname,
      },
      header: {
        //在请求头中传递用户的认证信息，向服务器表名身份，告诉服务器是哪个用户上传头像和呢称
        Authorization: `Bearer ${token}`,
      },
      success: (response) => {
        //获取服务器返回的呢称和头像地址
        const { nickname, avatar } = JSON.parse(response.data);
        //把它们存在本地以便 后面随时 获取
        //localStorage只能存字符中，但wx.setStorageSync可以存对象
        wx.setStorageSync("user", { nickname, avatar });
        //切换页签的路径
        wx.switchTab({
          url: "/pages/profile/profile",
          success: () => {
            //当页面切换完成后执行此回调
            let pages = getCurrentPages();
            //获取栈顶的profile页面的实例
            const currentPage = pages[pages.length - 1];
            //手工触发它的onLoad函数执行
            currentPage.onLoad();
          },
        });
      },
      fail: (error) => {
        console.log(error);
        wx.showToast({
          title: error.message,
          icon: "error",
        });
      },
    });
  },
});
